<template>
	<view class="layui-form-item">
		<label class="layui-form-label" v-if="title">{{title}}</label>
		<view class="layui-input-block">
			<view class="selectGroups clear">
				<view class="fl">
					<singleSelect :list="provinceList" :value="provinceId" titleKey="name" valueKey="id" :showDefault="false" @change="changeData($event,'provinceId')"></singleSelect>
				</view>
				<view class="fl">
					<singleSelect :list="cityList" :value="cityId" titleKey="name" valueKey="id" :showDefault="false" @change="changeData($event,'cityId')"></singleSelect>
				</view>
				<view class="fl">
					<singleSelect :list="districtList" :name="name" :value="districtId" titleKey="name" valueKey="id" :showDefault="false" @change="changeData($event,'districtId')"></singleSelect>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import cityKit from "./cityData.js" ;
	export default {
		name : "city" ,
		props:{
			title : {
				type : String ,
				default : "省市区"
			},
			name : {
				type : String ,
				default : ""
			},
			value : {
				type : String ,
				default : ""
			},
			disabled : {
				type : Boolean ,
				default : false
			},
		},
		created : function(e){
			
			this.initData();
		},
		
		watch:{
			value : function(res){
				this.initData();
			},
		},
		
		data() {
			return {
				provinceList : [],
				cityList : [],
				districtList : [] ,
				provinceId : null ,
				cityId : null ,
				districtId : null 
			};
		},
		methods:{
			
			initData : function(res){
				if(this.provinceList.length == 0){
					this.provinceList = cityKit.getProvinceList();
				}
				this.districtId = this.value ;
				var district = cityKit.findById(this.districtId);
				if(!!district){
					this.provinceId = district.grandpaId ;
					this.cityId = district.parentId ;
				}
				this.resetData();
			},
			
			resetData : function(res){
				if(this.provinceList.length == 0){
					return ;
				}
				if(!this.provinceId){
					this.provinceId = this.provinceList[0].id ;
				}
				this.cityList = cityKit.listByParentId(this.provinceId , 2);
				if(!this.cityId){
					this.cityId = this.cityList[0].id ;
				}
				this.districtList = cityKit.listByParentId(this.cityId , 3);
				if(!this.districtId){
					this.districtId = this.districtList[0].id ;
				}
			},
			
			changeData :function(res , name){
				this[name] = res.value ;
				if(name == 'provinceId'){
					this.cityId = null ;
					this.districtId = null ;
				}else if(name == 'cityId'){
					this.districtId = null ;
				}
				this.resetData();
			}
		}
	}
</script>

<style lang="scss">
.selectGroups{
	width: 100%;
	.fl{
		width: 32.66666666%;
		&+.fl{
			margin-left: 1%;	
		}
	}
}
</style>
